﻿package net.wangit.util;

import java.util.HashMap;
import java.util.Map;

public class StringUtil {

	public StringUtil() {
	}

	/**
	 * 将字符串数组strings转化为以seperator分割的字符串,与split功能相反
	 * 
	 * @param seperator
	 * @param strings
	 * @return
	 */
	public static String join(String seperator, String strings[]) {
		int length = strings.length;
		if (length == 0)
			return "";
		StringBuffer buf = (new StringBuffer(length * strings[0].length()))
				.append(strings[0]);
		for (int i = 1; i < length; i++) {
			buf.append(seperator).append(strings[i]);
		}
		return buf.toString();
	}

	/**
	 * 以flag分割字符串str，与join功能相反
	 * 
	 * @param str
	 * @param flag
	 * @return
	 */
	public static String[] split(String str, String flag) {
		if (str == null)
			return null;
		else
			return str.split(flag);
	}

	/**
	 * 忽略开头的flag,返回以flag分割字符串str的结果数组
	 * 
	 * @param str
	 * @param flag
	 * @return
	 */
	public static String[] splitIgnoreHeadFlag(String str, String flag) {
		if (str == null)
			return null;
		while (str.startsWith(flag)) {
			str = str.substring(1);
		}
		return str.split(flag);
	}

	public static String[][] split(String source, String rowSeparator,
			String colSeparator) {
		if (Checker.isEmpty(source) || Checker.isEmpty(rowSeparator)
				|| Checker.isEmpty(colSeparator))
			return null;
		String rows[] = split(source, rowSeparator);
		int rowLength = rows.length;
		int colLength = rows[0].split(colSeparator).length;
		for (int i = 1; i < rowLength; i++) {
			int length = rows[i].split(colSeparator).length;
			colLength = length <= colLength ? colLength : length;
		}

		String result[][] = new String[rowLength][colLength];
		String row[] = (String[]) null;
		for (int i = 0; i < rowLength; i++) {
			row = rows[i].split(colSeparator);
			for (int j = 0; j < colLength; j++)
				result[i][j] = j < row.length ? row[j] : "";

		}

		return result;
	}

	public static Map<String, String> split2Map(String source,
			String rowSeparator, String colSeparator) {
		String array[][] = split(source, rowSeparator, colSeparator);
		if (Checker.isEmpty(array) || array[0].length < 2)
			return null;
		Map<String, String> map = new HashMap<String, String>();
		for (int i = 0; i < array.length; i++)
			map.put(array[i][0], array[i][1]);

		return map;
	}

	public static String replace(String source, String target, String replace) {
		if (Checker.isEmpty(source) || Checker.isEmpty(target)
				|| replace == null || source.indexOf(target) < 0)
			return source;
		int s = 0;
		int e = 0;
		StringBuffer result = new StringBuffer();
		while ((e = source.indexOf(target, s)) >= 0) {
			result.append(source.substring(s, e));
			result.append(replace);
			s = e + target.length();
		}
		result.append(source.substring(s));
		return result.toString();
	}

	public static String clearSpace(String str) {
		return replace(str, " ", "");
	}

	public static String replaceIgnoreCase(String sourceString,
			String targetString, String replaceString) {
		if (sourceString == null)
			return null;
		if (Checker.isEmpty(targetString) || replaceString == null)
			return sourceString;
		String lcLine = sourceString.toLowerCase();
		String lcOldString = targetString.toLowerCase();
		int i = 0;
		if ((i = lcLine.indexOf(lcOldString, i)) >= 0) {
			char line2[] = sourceString.toCharArray();
			char newString2[] = replaceString.toCharArray();
			int oLength = targetString.length();
			StringBuffer buf = new StringBuffer(line2.length);
			buf.append(line2, 0, i).append(newString2);
			i += oLength;
			int j;
			for (j = i; (i = lcLine.indexOf(lcOldString, i)) > 0; j = i) {
				buf.append(line2, j, i - j).append(newString2);
				i += oLength;
			}

			buf.append(line2, j, line2.length - j);
			return buf.toString();
		} else {
			return sourceString;
		}
	}

	public static String find(String source, String target, String head,
			String tail) {
		if (source == null || source.equals(""))
			return "";
		String currStr = source;
		int index = 0;
		int s = 0;
		int e = 0;
		index = currStr.indexOf(head);
		if (index >= 0) {
			s = index + head.length();
			e = s;
			currStr = currStr.substring(e);
			index = currStr.indexOf(target);
		}
		if (index >= 0) {
			e += index + target.length();
			currStr = currStr.substring(e - s);
			index = currStr.indexOf(tail);
		}
		if (index >= 0) {
			e += index;
		} else {
			s = 0;
			e = 0;
		}
		return source.substring(s, e);
	}

	/**
	 * 获取以head开头，在head和随后的tail之间的字符串，如${user}中head="${", tail="}"则返回"user"
	 * 
	 * @param source
	 * @param head
	 * @param tail
	 * @return
	 */
	public static String find(String source, String head, String tail) {
		if (Checker.isEmpty(source))
			return null;
		int headIndex = 0;
		int tailIndex = 0;
		headIndex = source.indexOf(head);
		tailIndex = source.indexOf(tail, headIndex + head.length());
		if (headIndex >= 0 && tailIndex > 0 && tailIndex > headIndex)
			return source.substring(headIndex + head.length(), tailIndex);
		else
			return null;
	}

	public static boolean contain(String strings[], String string,
			boolean caseSensitive) {
		if (strings == null)
			return false;
		for (int i = 0; i < strings.length; i++)
			if (caseSensitive) {
				if (strings[i].equals(string))
					return true;
			} else if (strings[i].equalsIgnoreCase(string))
				return true;

		return false;
	}

	public static int countMatches(String str, String sub) {
		if (str == null || str.length() == 0 || sub == null
				|| sub.length() == 0)
			return 0;
		int count = 0;
		for (int idx = 0; (idx = str.indexOf(sub, idx)) != -1; idx += sub
				.length())
			count++;

		return count;
	}

	public static String getHexString(String sourceString) {
		if (Checker.isEmpty(sourceString))
			return "";
		else
			return encodeHex(sourceString.getBytes());
	}

	public static final String encodeHex(byte[] bytes) {
		StringBuffer buf = new StringBuffer(bytes.length * 2);
		for (int i = 0; i < bytes.length; i++) {
			if ((bytes[i] & 0xff) < 16)
				buf.append("0");
			buf.append(Long.toString(bytes[i] & 0xff, 16));
		}

		return buf.toString();
	}

	/**
	 * 16进制字符串转换为字节数组
	 * 
	 * @param hex
	 *            16进制字符
	 * @return
	 */
	public static final byte[] decodeHex(String hex) {
		char[] chars = hex.toCharArray();
		byte[] bytes = new byte[chars.length / 2];
		int byteCount = 0;
		for (int i = 0; i < chars.length; i += 2) {
			int newByte = 0;
			newByte |= hexCharToByte(chars[i]);
			newByte <<= 4;
			newByte |= hexCharToByte(chars[i + 1]);
			bytes[byteCount] = (byte) newByte;
			byteCount++;
		}

		return bytes;
	}

	private static final byte hexCharToByte(char ch) {
		switch (ch) {
		case '0':
			return 0x00;
		case '1':
			return 0x01;
		case '2':
			return 0x02;
		case '3':
			return 0x03;
		case '4':
			return 0x04;
		case '5':
			return 0x05;
		case '6':
			return 0x06;
		case '7':
			return 0x07;
		case '8':
			return 0x08;
		case '9':
			return 0x09;
		case 'a':
			return 0x0A;
		case 'b':
			return 0x0B;
		case 'c':
			return 0x0C;
		case 'd':
			return 0x0D;
		case 'e':
			return 0x0E;
		case 'f':
			return 0x0F;
		}
		return 0x00;
	}

	public static String fill(String str, int length, char c, boolean tail) {
		str = str != null ? str : "";
		int strLength = str.getBytes().length;
		StringBuffer result = new StringBuffer();
		while (strLength++ < length)
			result.append(c);
		if (tail)
			return (new StringBuilder(String.valueOf(str))).append(
					result.toString()).toString();
		else
			return (new StringBuilder(String.valueOf(result.toString())))
					.append(str).toString();
	}

	public static String repeat(String string, int times) {
		StringBuffer buf = new StringBuffer(string.length() * times);
		for (int i = 0; i < times; i++)
			buf.append(string);

		return buf.toString();
	}

	public static String replace(String template, String placeholder,
			String replacement, boolean wholeWords) {
		int loc = template.indexOf(placeholder);
		if (loc < 0) {
			return template;
		} else {
			boolean actuallyReplace = !wholeWords
					|| loc + placeholder.length() == template.length()
					|| !Character.isJavaIdentifierPart(template.charAt(loc
							+ placeholder.length()));
			String actualReplacement = actuallyReplace ? replacement
					: placeholder;
			return template.substring(0, loc)
					+ actualReplacement
					+ replace(template.substring(loc + placeholder.length()),
							placeholder, replacement, wholeWords);
		}
	}

	public static String replaceOnce(String template, String placeholder,
			String replacement) {
		int loc = template.indexOf(placeholder);
		if (loc < 0)
			return template;
		else
			return template.substring(0, loc) + replacement
					+ template.substring(loc + placeholder.length());
	}
}
